package com.moli.iov.admin.websocket.service.query.impl;

import com.moli.iov.admin.component.CacheManger;
import com.moli.iov.admin.websocket.service.AbstractWebSocketQueryService;
import com.moli.iov.admin.websocket.service.WebSocketQueryService;
import com.moli.iov.alarm.remote.IAlarmStatRemoteService;
import com.moli.iov.base.remote.IVehicleBaseRemoteService;
import com.moli.iov.real.service.IRealService;
import com.moli.iov.rest.GenericCode;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.sys.model.po.User;
import com.moli.iov.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author fudh
 * @ClassNmme AlarmStatisticsWServiceImpl
 * @date 2019/5/28 13:31
 * @Description: 首页车辆在线数，监控报警未解除数，车载终端报警未解除数，电子围栏报警未解除数的实时数据
 */
@Service("alarmStatisticsWService")
@Slf4j
public class AlarmStatisticsWServiceImpl extends AbstractWebSocketQueryService implements WebSocketQueryService {

    @Reference(group = "${service.group}", check = false)
    private IAlarmStatRemoteService alarmStatRemoteService;

    @Reference(group = "${service.group}", check = false)
    IRealService realService;

    @Reference(group = "${service.group}", check = false)
    IVehicleBaseRemoteService vehicleBaseRemoteService;

    @Resource
    CacheManger cacheManger;

    @Override
    public Object buildParam(String string) throws Exception {
        return JsonUtils.parse(string, Long.class);
    }

    @Override
    public RestResponse get(Object o,String token) {

        Map<String, Object> map = new HashMap<>();
        Map<String, Long> alarmCountMap = null;
        Long companyId = null;
        Integer onlineCount = 0;
        Integer totalCount = 0;

        try{
            User user = cacheManger.getUserByAuthHeader(token);
            if(user!=null && user.getCompanyId()!=null){
                companyId = user.getCompanyId();
            }

            //2、车辆监控报警数
            log.info("查询报警监控数，企业ID：{}",companyId);
            alarmCountMap = alarmStatRemoteService.getAlarmCount(companyId);

            //在线车辆
            List<String> onlineVinList = getOnlineVinList();

            //所有车辆
            Set<String> allVinSet = getAllVinSet(companyId);


            if(allVinSet!=null){
                totalCount = allVinSet.size();
            }

            if (onlineVinList != null) {
                for (String vin : onlineVinList) {
                    if (!StringUtils.isEmpty(vin) && allVinSet.contains(vin)) {
                        onlineCount++;
                    }
                }
            }

        }catch (Exception e){
            log.error(e.getMessage());
            alarmCountMap = new HashMap<>();
            alarmCountMap.put("fenceAlarmCount", 0L);
            alarmCountMap.put("deviceAlarmCount", 0L);
            alarmCountMap.put("offLineAlarmCount", 0L);
        }

        Integer offlineCount = totalCount - onlineCount;
        String offlineRatio = getRatio(offlineCount, totalCount);
        String onlineRatio = getRatio(onlineCount, totalCount);

        map.putAll(alarmCountMap);
        map.put("onlineCount", onlineCount.longValue());
        map.put("offlineRatio", offlineRatio);
        map.put("onlineRatio", onlineRatio);
        map.put("totalCount", totalCount);

        return RestResponse.success(map);
    }

    private String getRatio(Integer numerator, Integer denominator) {

        if (numerator != null && denominator != null && denominator != 0) {
            Float f1 = (float) numerator / denominator * 100;
            String res = new BigDecimal(f1).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
            log.info("numerator,denominator,result",numerator,denominator,res);
            return res;
        }
        return "0";
    }

    //根据企业id获取所有vin，如果companyId为空，则返回所有vin
    public Set<String> getAllVinSet(Long companyId) {
        RestResponse<List<String>> res = vehicleBaseRemoteService.listVinByCompanyId(companyId);
        if (res != null && res.flag && res.getData() != null) {
            return new HashSet<String>(res.getData());
        }
        return null;
    }

    private List<String> getOnlineVinList() {
        //1、车辆实时在线数
        RestResponse<List<String>> allOnlineRes = null;
        try {
            allOnlineRes = realService.queryAllOnlineList();
        } catch (Exception e) {
            log.error("查询车辆在线数量出错");
            return null;
        }
        if (allOnlineRes != null && allOnlineRes.getCode() == GenericCode.SUCCESS.getCode()) {
            List<String> data = allOnlineRes.getData();
            return data;
        }
        return null;

    }
}
